import java.net.ServerSocket;
import java.net.Socket;


public class Server extends Port {
    Socket currClient;
    String inetAddress;

    Server(Socket currClient, String inetAddress) {
        this.currClient = currClient;
        this.inetAddress = inetAddress;
    }

    public static void main(String[] args) {
        try {
            //初始化ServerSocket
            ServerSocket server = new ServerSocket(2000);
            System.out.println("Waiting for client connection...");


            while (true) {
                //阻塞等待客户端连接，初始化Socket
                Socket client = server.accept();
                String inetAddress = client.getInetAddress().toString().substring(1);
                System.out.println(client.getInetAddress().getHostName() + "/" + client.getInetAddress().getHostAddress() + " connection succeeded.");

                try {
                    // 发送信息线程
                    new SendThread(client).start();
                    // 接收信息线程
                    new ReplyThread(client, inetAddress).start();
                } catch (Exception e) {
                    System.out.println("异常关闭");
                } finally {
                    // SendThread和ReplyThread之一的线程释放了锁，才能关闭Socket
                    synchronized (lock) {
                        lock.wait();
                    }
                    client.close();
                }
            }

        } catch (Exception e) {
            System.out.println(e.getMessage());
        }

    }

}